<template>
	<view>
		<!-- 登录 -->
		<view class="box" v-if="props.type == 0">
			<view class="btnBox" @click="toLogin">
				<ButtonBar :btnValue="_t18('login')" />
			</view>
			<view class="account">
				{{ _t18('login_noAccount') }}？<span @click="$router.push('/sign-up')">{{
	         _t18('login_toRegister')
	       }}</span>
			</view>
		</view>
		<!-- 注册 -->
		<view class="box" v-if="props.type == 1">
			<view class="btnBox" @click="toResgister">
				<!--      <ButtonBar :btnValue="_t18('register')" />-->

				<view class="btn1">
					{{ _t18('register')}}
				</view>
			</view>
			<view class="account">
				{{ _t18('register_haveAccount') }}？<span @click="$router.push('/sign-in')">{{
	         _t18('register_toLogin')
	       }}</span>
			</view>
			<view class="info">
				{{ _t18('register_agree') }} {{ _getConfig('_APP_META_TITLE') }}
				<span
					@click="$router.push('/termsOfuse')">{{ _t18('register_howToUse') }}</span>&nbsp;{{ _t18('register_and') }}&nbsp;<span
					@click="$router.push('/privacyPolicy')">{{
	         _t18('register_private')
	       }}</span>
			</view>
		</view>
		<!-- 找回密码 -->
		<view class="box" v-if="props.type == 2">
			<view class="btnBox" @click="toForget">
				<ButtonBar :btnValue="_t18('btnConfirm', ['bitmake'])" />
			</view>
			<view class="info">
				{{ _t18('forget_findAccount') }}
				<span @click="toCustorm">{{ _t18('custorm_service', ['aams']) }}</span>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		REGISTER_REQUIRED_ACTIVECODE,
		REGISTER_REQUIRED_ACTIVECODE_MOBILE
	} from '@/config'
	import {
		_getConfig,
		_t18
	} from '@/utils/public'
	import ButtonBar from '@/components/common/ButtonBar/index.vue'
	import {
		signUp,
		signIn,
		backPwdToEmail
	} from '@/api/user'
	import {
		useRouter
	} from 'vue-router'
	import {
		useUserStore
	} from '@/store/user/index'
	import {
		useMainStore
	} from '@/store/index'
	import {
		useToast
	} from '@/hook/useToast'
	import {
		showToast,
		Toast
	} from 'vant'
	import {
		ref
	} from "vue";
	const {
		_toast
	} = useToast()
	const userStore = useUserStore()
	const router = useRouter()
	const props = defineProps({
		type: {
			type: Number
		},
		formDataToLogin: {
			type: Object
		},
		formDataToRegister: {
			type: Object
		},
		formDataToForget: {
			type: Object
		}
	})
	const emit = defineEmits(['refersh'])
	const toCustorm = () => {
		// showToast('请联系客服')
		_toast('custorm_service', ['aams'])
	}
	const refersh = () => {
		// 刷新验证码
		emit('refersh')
	}
	const mainStore = useMainStore()
	/**
	 * 登录
	 */
	const toLogin = () => {
		let formData = {}
		formData.code = props.formDataToLogin.code //验证码
		if (props.formDataToLogin.type == 1) {
			// 账号登录
			formData.loginName = props.formDataToLogin.username //用户名
			formData.loginPassword = props.formDataToLogin.password // 密码
			formData.signType = 3
			if (formData.loginName == '') {
				_toast('please_user')
				return
			} else if (formData.loginPassword == '') {
				_toast('please_pwd')
				return
			}
		} else if (props.formDataToLogin.type == 2) {
			// 邮箱登录
			formData.email = props.formDataToLogin.email //邮箱
			formData.signType = 1
			if (formData.email == '') {
				_toast('please_email')
				return
			}
		} else if (props.formDataToLogin.type == 3) {
			// 手机登录
			formData.phone = props.formDataToLogin.areaCode + props.formDataToLogin.mobile //区号+手机号
			formData.signType = 2
			if (props.formDataToLogin.mobile == '') {
				//手机号
				_toast('please_mobile')
				return
			}
		}
		// 验证码
		if (props.formDataToLogin.type == 2 || props.formDataToLogin.type == 3) {
			if (formData.code == '') {
				// _toast('请填写验证码')
				// msg = 'please_code'
				_toast('please_code')
				return
			}
		} else {
			if (formData.code == '' && mainStore.getISCode) {
				// _toast('请填写验证码')
				// msg = 'please_code'
				_toast('please_code')
				return
			}
		}
		loginSubmit(formData)
		// if (!msg) {
		//   loginSubmit(formData)
		// } else {
		//   _toast(msg)
		// }
	}
	// 登录接口
	const loginSubmit = (params) => {
		signIn(params)
			.then((res) => {
				if (res.code == '200' && res.data.satoken) {
					// _toast('登录成功！')
					_toast('login_success')
					let token = res.data.satoken
					userStore.setIsSign(true)
					userStore.setToken(token)
					setTimeout(() => {
						router.replace('/')
						userStore.getUserInfo()
					}, 500)
				} else {
					_toast(res.msg)
					if (props.formDataToLogin.type == 1) {
						refersh()
					}
				}
			})
			.catch((err) => {
				console.log(err)
			})
	}

	/**
	 * 注册
	 */
	const toResgister = () => {
		let formData = {}
		formData.loginPassword = props.formDataToRegister.password // 密码
		formData.activeCode = props.formDataToRegister.invitCode // 邀请码
		formData.code = props.formDataToRegister.code //验证码
		let msg = false
		// 普通注册
		// 邀请码必填
		if (formData.activeCode == '' || formData.activeCode == undefined) {
			// msg = 'plug_shareCode'
			_toast('plug_shareCode')
			return
		}
		if (props.formDataToRegister.type == 1) {
			formData.loginName = props.formDataToRegister.username //用户名
			formData.signType = 3
			if (formData.loginName == '') {
				//用户名
				_toast('please_user')
				return
			}
		} else if (props.formDataToRegister.type == 2) {
			formData.email = props.formDataToRegister.email //邮箱
			if (['aams'].includes(__config._APP_ENV)) {
				formData.phone = props.formDataToRegister.areaCode + props.formDataToRegister.mobile //区号+手机号
				if (props.formDataToRegister.mobile == '') {
					_toast('please_mobile')
					return
				}
			}
			// 邮箱注册
			formData.signType = 1
			if (formData.email == '') {
				_toast('please_email')
				return
			}
		} else if (props.formDataToRegister.type == 3) {
			// 手机注册
			formData.phone = props.formDataToRegister.areaCode + props.formDataToRegister.mobile //区号+手机号
			formData.signType = 2
			if (props.formDataToRegister.mobile == '') {
				_toast('please_mobile')
				return
			}
		}
		if (formData.loginPassword == '') {
			// msg = 'please_pwd'
			_toast('please_pwd')
			return
		} else if (props.formDataToRegister.password !== props.formDataToRegister.password2) {
			// msg = 'register_pwd_diff'
			_toast('register_pwd_diff')
			return
		} else if (REGISTER_REQUIRED_ACTIVECODE.includes(__config._APP_ENV) && formData.signType != 2) {
			// 邀请码必填
			if (formData.activeCode == '' || formData.activeCode == undefined) {
				// msg = 'plug_shareCode'
				_toast('plug_shareCode')
				return
			}
		} else if (
			REGISTER_REQUIRED_ACTIVECODE_MOBILE.includes(__config._APP_ENV) &&
			formData.signType == 2
		) {
			// 邀请码必填
			if (formData.activeCode == '' || formData.activeCode == undefined) {
				// msg = 'plug_shareCode'
				_toast('plug_shareCode')
				return
			}
		}
		// 验证码
		if (props.formDataToRegister.type == 2 || props.formDataToRegister.type == 3) {
			if (formData.code == '') {
				// _toast('请填写验证码')
				// msg = 'please_code'
				_toast('please_code')
				return
			}
		} else {
			if (formData.code == '' && mainStore.getISCode) {
				// _toast('请填写验证码')
				// msg = 'please_code'
				_toast('please_code')
				return
			}
		}
		registerSubmit(formData)
		// if (!msg) {
		//   // 注册
		//   registerSubmit(formData)
		// } else {
		//   _toast(msg)
		// }
	}
	const downloadUrl = ref("http://down.app.bitark.cc/")
	const handleAppDownload = async () => {
		try {
			// 1. 复制链接到剪贴板
			await navigator.clipboard.writeText(downloadUrl.value)

			// 2. 显示提示（根据环境适配）
			if (isInApp()) {
				// App内提示
				Toast({
					message: '下载链接已复制，请粘贴到浏览器打开',
					duration: 3000
				})

				// 可选：3秒后自动跳转浏览器（需要配置）
				// setTimeout(() => {
				//   window.location.href = downloadUrl.value
				// }, 3000)
			} else {
				// 浏览器环境提示
				Toast.success('链接已复制，请粘贴到地址栏下载')
			}
		} catch (err) {
			// 降级方案：手动复制提示
			fallbackCopy(downloadUrl.value)
		}
	}
	const isInApp = () => {
		return /(Android|iPhone|iPad).*Version\/\d+.*Mobile\/\w+/.test(navigator.userAgent)
	}

	const fallbackCopy = (text) => {
		const input = document.createElement('input')
		input.value = text
		document.body.appendChild(input)
		input.select()

		try {
			document.execCommand('copy')
			Toast('请手动粘贴链接到浏览器: ' + text)
		} catch {
			// 终极降级：直接跳转
			window.open(downloadUrl.value, '_blank')
		} finally {
			document.body.removeChild(input)
		}
	}
	// 注册接口
	const registerSubmit = (params) => {
		signUp(params)
			.then((res) => {
				// 刷新验证码
				if (res.code == '200') {
					// _toast('注册成功！')
					_toast('register_success')
					setTimeout(() => {
						// router.push('/sign-in')
						// router.push('/app-download?flag=home')
						handleAppDownload()
					}, 500)
				} else {
					_toast(res.msg)
					// 刷新验证码
					if (props.formDataToRegister.type == 1) {
						refersh()
					}
				}
			})
			.catch((err) => {
				console.log(err)
			})
	}
	// 忘记密码
	const toForget = () => {
		let formData = {}
		formData.email = props.formDataToForget.email //邮箱
		formData.newPwd = props.formDataToForget.password //密码
		formData.emailCode = props.formDataToForget.code //验证码
		let msg = false
		if (formData.email == '') {
			// _toast('请填写邮箱')
			// msg = 'please_email'
			_toast('please_email')
			return
		} else if (formData.newPwd == '') {
			// _toast('请填写密码')
			// msg = 'please_pwd'
			_toast('please_pwd')
			return
		} else if (formData.emailCode == '') {
			// _toast('验证码')
			// msg = 'please_code'
			_toast('please_code')
			return
		} else if (props.formDataToForget.password !== props.formDataToForget.password2) {
			// _toast('两次密码不一致')
			// msg = 'register_pwd_diff'
			_toast('register_pwd_diff')
			return
		}
		forgerPasswordSubmit(formData)
		// if (!msg) {
		//   // 忘记密码
		//   forgerPasswordSubmit(formData)
		// } else {
		//   _toast(msg)
		// }
	}
	const forgerPasswordSubmit = (params) => {
		backPwdToEmail(params.email, params.newPwd, params.emailCode)
			.then((res) => {
				if (res.code == '200') {
					// _toast('重置成功！')
					_toast('reset_success')
					setTimeout(() => {
						router.push('/sign-in')
					}, 500)
				} else {
					_toast(res.msg)
				}
			})
			.catch((err) => {
				console.log(err)
			})
	}
</script>

<style lang="scss" scoped>
	* {
		font-size: 14px;
		color: #1e293b;
	}

	.box {
		padding: 0;

		.btnBox {
			margin-top: 40px;
			position: relative;
			display: block;


			&::before {
				content: '';
				position: absolute;
				top: -20px;
				left: 50%;
				transform: translateX(-50%);
				width: 80px;
				height: 2px;
				background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
				border-radius: 1px;
			}
		}

		.account {
			padding: 32px 0 20px;
			font-size: 15px;
			text-align: center;
			color: #64748b;

			span {
				color: #17AC74;
				cursor: pointer;
				transition: all 0.2s ease;
				padding: 6px 12px;
				border-radius: 8px;
				font-weight: 600;

				&:hover {
					color: #14a085;
					background: rgba(23, 172, 116, 0.05);
				}
			}
		}

		.info {
			margin-top: 28px;
			text-align: center;
			font-size: 13px;
			line-height: 1.6;
			color: #64748b;

			span {
				color: #17AC74;
				cursor: pointer;
				transition: all 0.2s ease;
				padding: 4px 8px;
				border-radius: 6px;
				font-weight: 500;

				&:hover {
					color: #14a085;
					background: rgba(23, 172, 116, 0.05);
				}
			}
		}
	}

	div {
		text-align: center;
		border-radius: 12px;
		font-size: 16px;
		padding: 18px 0;
		font-weight: 600;
		transition: all 0.3s ease;
	}

	.btn1 {
		background: var(--ex-btn-background-color);
		color: white !important;
		border: none !important;
		box-shadow: 0 4px 16px var(--ex-btn-background-color);
		position: relative;
		overflow: hidden;
		display: block;
		text-align: center;
		padding: 15px 0;
		border-radius: 6px;
		margin-bottom: 20px;

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: -100%;
			width: 100%;
			height: 100%;
			background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
			transition: left 0.5s ease;
		}

		&:hover {
			transform: translateY(-2px);
			box-shadow: 0 8px 24px rgba(23, 172, 116, 0.3);

			&::before {
				left: 100%;
			}
		}

		&:active {
			transform: translateY(0);
		}
	}

	// 响应式设计
	@media (max-width: 480px) {
		.box {
			.btnBox {
				margin-top: 32px;
			}

			.account {
				padding: 28px 0 16px;
				font-size: 14px;
				margin-bottom: 15px;

				span {
					color: #ffbe40;
				}
			}

			.info {
				margin-top: 24px;
				font-size: 12px;

				span {
					color: #ffbe40;
				}
			}
		}

		div {
			font-size: 15px;
			padding: 16px 0;
		}
	}
</style>